package com.examiner.service.impl;

import com.examiner.bean.Examiner;
import com.examiner.bean.Manager;
import com.examiner.dao.ExaminerDao;
import com.examiner.page.QueryInfo;
import com.examiner.service.ExaminerService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import java.util.List;

@Service
public class ExaminerServiceImpl implements ExaminerService {
    @Resource
    ExaminerDao examinerDao;

    @Override
    public Examiner hasUserName(String userName) {
        Examiner examiner = examinerDao.findExaminerByUserName(userName);
        return examiner;
    }

    /**
     * 根据ID判断是否存在
     * @param id
     * @return
     */
    @Override
    public Boolean existById(Integer id) {
        return examinerDao.existsById(id);
    }


    @Override
    public Examiner saveExaminer(Examiner examiner) {
        return examinerDao.save(examiner);
    }

    @Override
    public Examiner findOne(Integer id) {
        return examinerDao.getOne(id);
    }

    @Override
    public Boolean updateManagerPassword(Integer id, String encodePsw) {
        int i = examinerDao.updatePassword(id, encodePsw);
        System.out.println(i);
        if (i!= 1) return false;
        return true;
    }

    @Override
    public List<Examiner> getExaminerList(QueryInfo queryInfo) {
        // 1. 新建 spec
        Specification spec = (Specification) (root, cq, cb) -> {
            // 1.获取属性
            Path userName = root.get("userName");
            // 2. 封装查询条件
            return cb.like(userName.as(String.class), queryInfo.getQuery()+"%");
        };
        // 2. 新建 pageable
        PageRequest pageRequest = PageRequest.of(queryInfo.getPageNum() - 1, queryInfo.getPageSize(), Sort.Direction.ASC,"id");
        Page page = examinerDao.findAll(spec, pageRequest);
        System.out.println(page);
        return page.getContent();
    }

    @Override
    public void deleteManager(Integer id) {
        examinerDao.deleteById(id);
    }

    @Override
    public int getTotal(String query) {
        return examinerDao.getTotal(query);
    }

    @Override
    public List<Examiner> getExaminerListByQuery(String query) {
        return examinerDao.getExaminerListByQuery(query);
    }

}
